//
//  CardViewController.m
//  ICard
//
//  Created by fanshao on 11-2-27.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CardViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "MyCustomTableVeiwCell.h"
#import "ContactInfo.h"
#import "UserInfo.h"
#import "ICardAppDelegate.h"
#import "InofTabbarContrller.h"


@implementation CardViewController
@synthesize imageButton;


@synthesize userNameTextField;
@synthesize phoneNumberTextField;
@synthesize saveButton;
@synthesize headSelButton;
@synthesize contactTableView;

@synthesize contactDataArray;

@synthesize receivedData;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.contactDataArray = [NSMutableArray arrayWithCapacity:5];
	mycard = [[MyCard alloc] init];
	
	[self.userNameTextField setDelegate:self];
	self.userNameTextField.returnKeyType = UIReturnKeyDone;
	self.userNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
	self.userNameTextField.text =@"test";
	
	[self.phoneNumberTextField setDelegate:self];
	self.phoneNumberTextField.returnKeyType = UIReturnKeyDone;
	self.phoneNumberTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
	self.phoneNumberTextField.text =@"13588879256";
	
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[mycard release];
	[contactDataArray release];
    [super dealloc];
}

- (IBAction)getImage:(id)sender{
	myAlertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
	[myAlertView setFrame:CGRectMake(0, 0, 70, 70)];
	//UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
	
	UIButton *buttonPhotoLibrary = [UIButton buttonWithType:UIButtonTypeCustom];
	[buttonPhotoLibrary setFrame:CGRectMake(10.0f, 10.0f, 60, 30)];
	[buttonPhotoLibrary setTitle:@"相册" forState:UIControlStateNormal];
	[buttonPhotoLibrary addTarget:self action:@selector(getImageFromLibrary:) forControlEvents:UIControlEventTouchUpInside];
	[myAlertView addSubview:buttonPhotoLibrary];
	
	
	UIButton *buttonPhoto = [UIButton buttonWithType:UIButtonTypeCustom];
	[buttonPhoto setFrame:CGRectMake(10.0f, 50.0f, 60, 30)];
	[buttonPhoto setTitle:@"相机" forState:UIControlStateNormal];
	[buttonPhoto addTarget:self action:@selector(getImageFromPhoto:) forControlEvents:UIControlEventTouchUpInside];

	[myAlertView addSubview:buttonPhoto];
	
	[myAlertView show];
	//[myAlertView release];
}
- (IBAction)saveInfo:(id)sender{

	self.receivedData = [NSMutableData data];
	//[[UserInfo shardUserInfo] 
	mycard.myname = self.userNameTextField.text;
	mycard.phoneNumber = self.phoneNumberTextField.text;
	
	mycard.phoneNumber = self.phoneNumberTextField.text;
	[[[UserInfo shardUserInfo] cardArray] addObject:mycard];
	[[UserInfo shardUserInfo] savePref];
	NSLog(@"card array is %@", [[[UserInfo shardUserInfo] cardArray] description]);
	InofTabbarContrller *firstViewController = [[InofTabbarContrller alloc] init];
	if(firstViewController == nil)
		return;
	else
	{
		[firstViewController setTitle:@"我的名片"];
		[[self navigationController] pushViewController:firstViewController animated:YES];
		
	}
	[firstViewController release];
	//UITabBarController*temp =  [(ICardAppDelegate*)[[UIApplication sharedApplication] delegate] tabBarController];
	//[self.navigationController pushViewController:[(ICardAppDelegate*)[[UIApplication sharedApplication] delegate] tabBarController] animated:YES];
	
	/*NSString *requestStirng =[NSString stringWithFormat: @"ppt=%@&cardname=%@&vcard=%@myname=%@&head=%@sound=%@&view_location=%d&view_online_info=%@headtype=%@soundtype=%@&id=%@mobile=%@", [[UserInfo shardUserInfo] ppt], @"test", @"test",userName, @"test", @"22",1, @"dd", @" dd", @"dd",@"dd", phoneNumber];
	NSLog(@"requstring is %@", requestStirng);
	NSData *postData = [NSData dataWithBytes:[requestStirng UTF8String] length:[requestStirng length]];
	
	
	
	NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[kSaveCardURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	[connectionRequest setHTTPMethod:@"POST"];
	[connectionRequest setTimeoutInterval:120.0];
	[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	[connectionRequest setHTTPBody:postData];
	
	NSURLConnection *connection = [[NSURLConnection alloc]
								   initWithRequest:connectionRequest
								   delegate:self];
	[connection autorelease];*/
	
}
- (IBAction)headSelect:(id)sender{
}


- (IBAction)getImageFromPhoto:(id)sender{
	[myAlertView dismissWithClickedButtonIndex:0 animated:YES];
	//[myAlertView removeFromSuperview];
	[myAlertView release];
	UIImagePickerController *picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
	picker.sourceType = UIImagePickerControllerSourceTypeCamera;
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}

- (IBAction)getImageFromLibrary:(id)sender{
	[myAlertView dismissWithClickedButtonIndex:0 animated:YES];
	
	UIImagePickerController *picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
	picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}

- (IBAction)selectContactType:(id)sender{
	
}
- (IBAction)addContactInfo:(id)sender{
	ContactInfo *contact = [[ContactInfo alloc] init];
	contact.type = curType;
	[self.contactDataArray addObject:contact];
	[self.contactTableView reloadData];
}

- (void)deleteCell:(id)sender{
	NSIndexPath *path = [self.contactTableView indexPathForCell:sender];
	[self.contactDataArray removeObjectAtIndex:path.row];
	[self.contactTableView reloadData];
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
	mycard.myImage = image;
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
	//mycard.myImage = [picker image];
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
	[picker dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [contactDataArray count] ;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    MyCustomTableVeiwCell *cell = (MyCustomTableVeiwCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[MyCustomTableVeiwCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
	[cell setDeleteDelegate:self];
	// Configure the cell.
	//[cell setText:@"cell"];
	

    return cell;
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 50;
}
#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
}

#pragma mark -
#pragma mark TextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
	
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	[textField resignFirstResponder];
	//[self GetChineseName];
	if (textField == self.userNameTextField) {
		[mycard setMyname:textField.text];
	}
	else {
		[mycard setPhoneNumber:textField.text];
	}

	return YES;
}

#pragma mark connection delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	
	[self.receivedData appendData:data];
	NSLog(@"self.reveivedData is %@", self.receivedData);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	
	NSString *temp = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding] ;
	NSLog(@"temp is %@", temp);
	NSNumber *number =  [[temp JSONValue]  valueForKey:@"rlt"] ;
	
	
	int ret = [number intValue];
	if (ret) {
		NSString *errorInfo = [[temp JSONValue] valueForKey:@"txt"];
		NSLog(@"errorInfo is %@",errorInfo);
		UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't log in!", nil)
														   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
		
		[alerView show];
		[alerView release];
		
	}
	else {
		NSArray *cardsArray = [[temp JSONValue] valueForKey:@"cards"];
		NSLog(@"the count is %d", [cardsArray count]);
		MyCard *myCard  = [[MyCard alloc] init];
		for (NSDictionary *dict in cardsArray) {
			myCard.cardId = [dict objectForKey:@"cardid"];
			myCard.myname = [dict objectForKey:@"myname"];
			myCard.cardName = [dict objectForKey:@"cardname"];
			myCard.vcard = [dict objectForKey:@"vcard"];
		}
		NSString *pt = [[temp JSONValue] valueForKey:@"ppt"];
		[[UserInfo shardUserInfo] setPpt:pt];
	}
	
}
- (void)didFailDownloadWithError:(NSError *)error {
	//[self stopAnimating];
	//[self processError:error];
	NSString *str = [error localizedDescription];
	UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:str
													   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
	
	[alerView show];
	[alerView release];
	
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[self didFailDownloadWithError:error];
	
	
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	BOOL disconnect = NO;
	//NSLog(@"Response, the statuscode is %d", [(NSHTTPURLResponse *)response statusCode]);	//[self setResponse:response];
	
	switch([(NSHTTPURLResponse *)response statusCode]) {
		case 200:
		case 206:
			break;
		case 304:
			disconnect = YES;
			break;
		case 400:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't get the Chinese name", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			disconnect = YES;
		}
			break;
			
			break;
			
		case 404:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't get the Chinese name", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			
			//[self connection:connection didFailWithError:theError];
			//[self stopAnimating];
			
			disconnect = YES;
		}
			break;
		case 416:
		{
			NSError *theError = [NSError errorWithDomain:@"CustomDomain"
													code:416 
												userInfo:[NSDictionary dictionaryWithObject:@"Range is missmatch."
																					 forKey:NSLocalizedFailureReasonErrorKey]];
			[self connection:connection didFailWithError:theError];
			[self stopAnimating];
			disconnect = YES;
		}
			break;
		case 403:
		case 401:
		case 500:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Server error Name Get", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			//[self stopAnimating];
		}
			break;
		default:
		{
			NSError *theError = [NSError errorWithDomain:@"CustomDomain"
													code:666
												userInfo:[NSDictionary dictionaryWithObject:@"Unknown error."
																					 forKey:NSLocalizedFailureReasonErrorKey]];
			[self connection:connection didFailWithError:theError];
		}
			disconnect = YES;
			break;
	}
	
}

@end
